package com.bigfans.catalogservice.service.sku;

import com.bigfans.catalogservice.dao.StockDAO;
import com.bigfans.catalogservice.exception.OutOfStockException;
import com.bigfans.catalogservice.model.SKU;
import com.bigfans.catalogservice.model.Stock;
import com.bigfans.catalogservice.model.StockLog;
import com.bigfans.framework.dao.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service(StockServiceImpl.BEAN_NAME)
public class StockServiceImpl extends BaseServiceImpl<Stock> implements StockService  {

    public static final String BEAN_NAME = "stockService";

    private StockDAO stockDAO;

    @Autowired
    private StockLogService stockLogService;

    @Autowired
    public StockServiceImpl(StockDAO stockDAO) {
        super(stockDAO);
        this.stockDAO = stockDAO;
    }

    @Override
    @Transactional
    public Integer orderStockOut(String orderId, String userId, Map<String, Integer> prodMap) throws Exception {
        List<StockLog> stockLogs = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : prodMap.entrySet()) {
            Integer count = stockDAO.stockOut(entry.getKey(), entry.getValue());
            if(count == 0){
                throw new OutOfStockException(entry.getKey());
            }
            StockLog log = new StockLog();
            log.setOrderId(orderId);
            log.setUserId(userId);
            log.setProdId(entry.getKey());
            log.setQuantity(entry.getValue());
            log.setDirection(StockLog.DIR_OUT);
            stockLogs.add(log);
        }
        return stockLogService.batchCreate(stockLogs);
    }

    @Transactional
    public void revertOrderUsedStock(String orderId) throws Exception{
        List<StockLog> stockLogs = stockLogService.listOrderStockOutLog(orderId);
        List<StockLog> revertLogs = new ArrayList<>();
        for(StockLog stockLog : stockLogs){
            String prodId = stockLog.getProdId();
            Integer quantity = stockLog.getQuantity();
            stockDAO.stockIn(prodId , quantity);
            // 添加回滚日志
            StockLog revertLog = new StockLog();
            revertLog.setProdId(prodId);
            revertLog.setQuantity(quantity);
            revertLog.setOrderId(stockLog.getOrderId());
            revertLog.setUserId(stockLog.getUserId());
            revertLog.setDirection(StockLog.DIR_IN);
            revertLog.setReason(StockLog.REASON_ORDERREVERT);
            revertLogs.add(revertLog);
        }
        stockLogService.batchCreate(revertLogs);
    }

    @Override
    public Stock getByProd(String pid) throws Exception {
        return stockDAO.getByProd(pid);
    }

    @Override
    public Stock getBySkuValKey(String valKey) throws Exception {
        return stockDAO.getBySkuValKey(valKey);
    }
}
